﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EarthGrid.core
{
    public class LonLat
    {
        private int du = 0;
        private int fen = 0;
        private double miao = 0.0;
        private LonLatEnum type;

        /// <summary>
        /// 度，可以没有分
        /// </summary>
        public int Du { get => du; set => du = value; }

        /// <summary>
        /// 分，必须有度的具体有效值，可以没有秒
        /// </summary>
        public int Fen { get => fen; set => fen = value; }

        /// <summary>
        /// 秒，必须有分的具体有效值，可以没有小数
        /// </summary>
        public double Miao { get => miao; set => miao = value; }

        /// <summary>
        /// 是经度还是纬度
        /// </summary>
        public LonLatEnum Type { get => type; set => type = value; }

        public LonLat() { }
        public LonLat(LonLatEnum type, int du, int fen, double miao)
        {
            this.type = type;
            this.du = du;
            this.fen = fen;
            this.miao = miao;
        }

        /// <summary>
        /// 转换成有效的十进制，超出度分秒数值范围的不计
        /// </summary>
        /// <returns></returns>
        public double to十进制()
        {
            double d = du;
            bool b = du > 0 || fen > 0 || miao > 0;
            if (b)
            {
                if (type == LonLatEnum.lon)
                {
                    d = du > 180 ? 180 : du;
                } else if (type == LonLatEnum.lat)
                {
                    d = du > 90 ? 90 : du;
                }
                d += (fen > 60 ? 1 : (double)fen / 60);
                d += miao > 60 ? (double)1 / 60 : (double)miao / 3600;
            }
            else
            {
                if (type == LonLatEnum.lon)
                {
                    d = du < -180 ? -180 : du;
                }
                else if (type == LonLatEnum.lat)
                {
                    d = du < -90 ? -90 : du;
                }
                d += fen < -60 ? -1 : (double)fen / 60;
                d += miao < -60 ? (double)-1 / 60 : (double)miao / 3600;
            }
            return d;
        }

        public string ToString()
        {
            return du + "°" + fen + "′" + miao + "″";
        }

        public LonLat copy()
        {
            return new LonLat(type, du, fen, miao);
        }
    }
}
